package com.attilax.sql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.lang3.StringUtils;

import aaaCfg.ConnectionImp;
import aaaCfg.IocX;

 

import com.attilax.biz.seo.getConnEx;
import com.attilax.io.pathx;
import com.attilax.lang.Global;
import com.attilax.persistence.DBCfg;
import com.attilax.persistence.DbutilX;
import com.attilax.time.timeUtil;
import com.attilax.token.TokenService;
import com.attilax.user.NotLoginEx;
import com.google.inject.Inject;


/**
 * q317  
 * com.attilax.sql.SqlService
 * @author Administrator
 *
 */
public class SqlServiceAbs {

	 

	public Object exe(String sql) {
		if(sql.trim().toLowerCase().startsWith("update") || sql.trim().toLowerCase().startsWith("insert"))
		{
			 
			return  execSql_retInt(sql);
		}
		return executeQuery(sql);
		// TODO Auto-generated method stub
		
	}
	
	public SqlServiceAbs(DBCfg cfg) {
		this.dbcfg=cfg;
	}
	
	
 
	public SqlServiceAbs(Connection conn) {
		this.conn=conn;
	}
	
	
	


	public SqlServiceAbs() {
	System.out.println("-------db til  no para ini:SqlService");
	}


	/**
	@author attilax 鑰佸搰鐨勭埅瀛�
	@since   p1p g_r_w
	 
	 */
	public static void main(String[] args) {
//		 String sql = " SELECT * FROM `mall_shop_info` sp left join  mall_user_info  ui on  sp.user_id=ui.user_id where sp.user_id=8 ";
//		//  sql= " update mall_shop_info set shop_intro='myintro5' where shop_id=8 ";
//		//  sql=sql+" ; update  mall_user_info set  user_mobile='1358891563'    where user_id=8 ";
//sql="SELECT * FROM  mall_user_info   where  user_id=6 ; SELECT * FROM  mall_user_info   where  user_id=8 ";
//		
//  sql="select * from hx_car where name like '%璞溅%'";
//		 DbutilX c= IocX.getBean(DbutilX.class);
//	//	 System.out.println(c.update(sql));
//	 	 List li=c.findBySql(sql);
		 
//	 	 ApiX2 hc=new ApiX2();
//		 hc.hbx=c;
//		
		 String sql="select * from gv_material";
			DbutilX dx= IocX.getBean(DbutilX.class);
			 List<Map> li=dx.findBySql(sql);
 		//  System.out.println(core.toJsonStrO88(li));
		 System.out.println("--f");

	}
//	@   //Inject
	protected
	Connection conn;
	@Inject
	protected
	DBCfg dbcfg;
	//String path = pathx.classPath() + "/website.properties";
	public Connection getConnection()  {
		if(this.conn instanceof ConnectionImp)
			this.conn=null;
		
		if(this.conn!=null)
			return this.conn;
		// com.microsoft.sqlserver.jdbc.SQLServerDriver
	
		//System.out.println(PropX.getConfig(path, "jdbc.url"));
		
		
	
		try {

			Class.forName(dbcfg.getDriver());
		} catch (ClassNotFoundException e) {
			throw new connEx("Class.forName driver err,drive class name is :  "+dbcfg.getDriver(),e);
		}
	//	Connection conn;
//
//		conn = DriverManager.getConnection(dbcfg.getUrl(), dbcfg.getUser(), dbcfg.getPassword());
//		
//		try {
//
//			Class.forName("com.mysql.jdbc.Driver");
//		} catch (ClassNotFoundException e) {
//			throw new getConnEx("getconnex" + e.getMessage());
//		}
		Connection conn;
		try {
			conn = DriverManager.getConnection(
					dbcfg.getUrl(),
					dbcfg.getUser(),
					dbcfg.getPassword());
			System.out.println("get conn: "+ conn+" at:"+timeUtil.Now_CST());
			
		} catch (SQLException e) {
			throw new connEx("getconnex" + e.getMessage());
		}
		return conn;
	}
	
	public List<Map> execSql(String sql)
	{
		if(sql.trim().toLowerCase().startsWith("update") || sql.trim().toLowerCase().startsWith("insert"))
		{
			int intx = update(sql);
			 List li=new ArrayList ();
			 li.add(intx);
			return li;
		}
		return findBySql(  sql);
		
	}
	
	
	public int executeUpdate(Connection conn, String string) {
		PreparedStatement prepareStatement;
		ResultSet resultSet;
		try {
			prepareStatement = conn.prepareStatement(string);
		return 	prepareStatement.executeUpdate() ;
			 
		} catch (SQLException e) {
			 
			 throw new RuntimeException(e);
		}
	}

	public Map uniqueResult(String $sql) {
		List li=findBySql($sql);
		return (Map) li.get(0);
	}
	
	public List findBySql(String sql)  {
		Connection conn;
		 try{
			conn = getConnection();

			// 鍒涘缓涓�涓猀ueryRunner
			QueryRunner queryRunner = new QueryRunner(true);
			List<Map<String, Object>> list;

			list = queryRunner.query(conn,
					sql,
					new MapListHandler());
		 
			return list;
	 
		 }
		catch (Exception e) {

			e.printStackTrace();
			throw new RuntimeException(e);
		}

	}
	public int executeUpdate(String sql) {
		// TODO Auto-generated method stub
		sql = parseVar(sql);
		return  execSql_retInt(sql);
	}
	 	
	public List executeQuery(String sql)
	{
		if(sql==null || sql.trim().length()==0)
			throw new RuntimeException("sql is null or empty");
		sql = parseVar(sql);
// new RuntimeException(" no implt" );
return findBySql(  sql);
	}

	private String parseVar(String sql) {

		// if(req.getParameter("$utype")!=null)
		// {
		HttpServletRequest req = Global.req.get();
//		if(req==null)
//			return sql;
//		String utype = "user";// defval
//		if (req.getParameter("$utype") != null)
//			utype = req.getParameter("$utype");
//
//		tkSrv.setModule(utype + "Mod");
//
//		List<String> params = new ParamUtil().findSqlParam(sql);
//		for (String p : params) {
//			if (p.equals("$uid$")) {
//				String getuid = tkSrv.getuid(req);
//				if (StringUtils.isEmpty(getuid))
//					throw new NotLoginEx("NotLoginEx");
//				sql = sql.replace("$uid$", tkSrv.getuid());
//			}
//		}
		// }
		return sql;
	}
	public Integer execSql_retInt(String sql)
	{

// new RuntimeException(" no implt" );
return update(  sql);
	}
	
	
	public int update(String sql)  {
		Connection conn;
		 try{
			conn = getConnection();

			// 鍒涘缓涓�涓猀ueryRunner
			QueryRunner queryRunner = new QueryRunner(true);
			int list;

			list = queryRunner.update(conn, sql);
		 
			return list;
	 
		 }
		catch (Exception e) {

			e.printStackTrace();
			throw new RuntimeException(e);
		}

	}

	/**
	attilax    2016骞�4鏈�25鏃�  涓嬪崍5:14:42
	 * @param s
	 * @return
	 */
	public Map executeQueryFirstRow(String s) {
		List li= executeQuery(s);
		if(li.size()==0)
			return null;
		return (Map) li.get(0);
		
	}



}
